require 'fastercsv'

class RootController < ApplicationController

  # user home page
  def home
      if (params[:RefreshRate] != '' && params[:RefreshRate] =~ /^\d+$/) 
          @refreshRate = params[:RefreshRate];
      end

      # 10 highest priority tasks that users owns
      @my_hightest_priority_tasks = session[:user].highest_priority_tasks();
      # 10 newest unowned tasks
      @unowned_tasks = Task.unowned_tasks();
      # project list
      @opened_projects = Project.opened_projects;
  end

  # search
  def search 
      @projects = Project.opened_projects;
      @users = User.active_users;
      @statuses = StatusTask.find(:all);
      return unless params[:do];

      get_searched_tasks; 
  end

  def export
      get_searched_tasks; 
      stream_csv do |csv|
          csv << ["Task ID","Subject","Project","Priority","Status","Created","Requestor","Owner","Time left","Time worked"]
          @tasks.each do |task|
              csv << [task.task_id, task.subject, task.project.name, task.priority, task.status.name, task.created.strftime('%F %T'), task.requestor, task.estimated_time - task.time_worked, 0, task.time_worked]
          end
      end 
  end

 private
  def stream_csv
      filename = 'tasks.csv';  
      
      #this is required if you want this to work with IE        
      if request.env['HTTP_USER_AGENT'] =~ /msie/i
       headers['Pragma'] = 'public'
       headers["Content-type"] = "text/plain" 
       headers['Cache-Control'] = 'no-cache, must-revalidate, post-check=0, pre-check=0'
       headers['Content-Disposition'] = "attachment; filename=\"#{filename}\"" 
       headers['Expires'] = "0" 
      else
       headers["Content-Type"] ||= 'text/csv'
       headers["Content-Disposition"] = "attachment; filename=\"#{filename}\"" 
      end
      
      render :text => Proc.new { |response, output|
          csv = FasterCSV.new(output, :row_sep => "\r\n", :force_quotes => true) 
          yield csv
      }
  end
 
  def get_searched_tasks
      conditions = [];

      ok = 0;
      if params[:subject] != nil
          conditions.push("subject like '%%" + params[:subject] + "%%'");
	  ok = 1;
      end
      if params[:project] != nil
          conditions.push('project_fk = ' + params[:project]);    
	  ok = 1;
      end	  
      if params[:requestor] != nil
          conditions.push("owner like '%%" + params[:requestor] + "%%'");
	  ok = 1;
      end	  
      if params[:status] != nil
          conditions.push('status_fk = ' + params[:status]);
	  ok = 1;
      end	  
      if params[:priority] != nil
          conditions.push('priority = ' + params[:priority]);
	  ok = 1;
      end	  
      if params[:time_worked] =~ /^\d+$/
          conditions.push('time_worked = ' + params[:time_worked]);    
	  ok = 1;
      end	  
      if params[:owner] =~ /^\d+$/
          conditions.push('owner = ' + params[:owner]);    
	  ok = 1;
      end	      

      @tasks = Task.find(:all,
                         :conditions => ok == 1 ? [conditions.join(' and ')] : nil );
      return @tasks;   
  end

end
